package com.myfum.mobile.tetris.views
{
	import com.myfum.mobile.tetris.Config;
	import com.myfum.mobile.tetris.data.TetrisMap;
	import com.myfum.mobile.tetris.data.cubes.CubeData;
	import com.myfum.mobile.tetris.data.cubes.DropingCubeData;
	import com.myfum.mobile.tetris.events.ClearedLineEvent;
	import com.myfum.mobile.tetris.events.MapEvent;
	import com.myfum.mobile.tetris.interfaces.IShape;
	import com.myfum.mobile.tetris.utils.MaterialFactory;
	
	import flare.core.Pivot3D;
	import flare.materials.Shader3D;
	import flare.materials.filters.ColorFilter;
	import flare.primitives.Cube;
	
	import org.robotlegs.mvcs.Mediator;
	
	public class TetrisMediator extends Mediator
	{
		[Inject]
		public var view:Tetris;
		[Inject]
		public var map:TetrisMap;
		
		public function TetrisMediator()
		{
			super();
		}
		
		override public function onRegister():void{
			eventMap.mapListener(eventDispatcher, MapEvent.MAP_CHANGE, onMapChange);
			eventMap.mapListener(eventDispatcher, ClearedLineEvent.LINE_CLEARED, onLineCleared);
			initialize();
		}
		
		private function initialize():void{
			var m:Shader3D = MaterialFactory.getMaterial(view.data);
			
			var cube:Cube;
			for each(var d:DropingCubeData in view.data.cubes){
				cube = getCube(d);
				view.addChild(cube);
				
				cube.setMaterial(m);
			}
		}
		
		private function onMapChange(e:MapEvent):void{
			if(e.now == view.data){
				update(e.now);
			}
		}
		
		private function onLineCleared(e:ClearedLineEvent):void{
			for each(var i:int in e.lines){
				clearLine(i-1);
			}
		}
		
		private function clearLine(line:int):void{
			var arr:Array = [];
			for each(var data:CubeData in view.data.cubes){
				var index:int = view.data.cubes.indexOf(data);
				if(data.y == line){
					//arr.push(view.children[index]);
					view.children[index].visible = false;
				}
			}
			/*while(arr.length > 0){
				view.removeChild(arr.pop());
			}*/
			for each(var child:Pivot3D in view.children){
				if(child.visible){
					child.y -= Config.CUBE_SIZE_3D;
				}
			}
		}
		
		private function update(data:IShape):void{
			var cube:Cube;
			var cd:CubeData;
			for(var i:int = 0; i < data.cubes.length; i++){
				cube = view.children[i] as Cube;
				cd   = data.cubes[i];
				cube.x = cd.x * Config.CUBE_SIZE_3D;
				cube.y = (Config.STAGE_HEIGHT - cd.y)*Config.CUBE_SIZE_3D;
			}
		}
		
		private function getCube(data:DropingCubeData):Cube{
			var c:Cube = new Cube('', Config.CUBE_SIZE_3D, Config.CUBE_SIZE_3D, Config.CUBE_SIZE_3D);
			c.x = data.x * c.width;
			c.y = (Config.STAGE_HEIGHT - data.y) * c.height;
			return c;
		}
	}
}